<template>
	<el-card class="box-card">
		<div slot="header" class="clearfix">
			<span>轮播图管理</span>
			<el-button v-permission="'promotion:slide:create'" type="primary" plain icon="el-icon-circle-plus-outline"
				@click="insert_dialog_visible = true">
				添加轮播
			</el-button>
		</div>
		<el-table :data="tableData">
			<el-table-column prop="slide_id" label="#"></el-table-column>
			<el-table-column label="轮播图片" width="200">
				<template slot-scope="scope">
					<el-image style="width: 150px;" :src="scope.row.picture"></el-image>
				</template>
			</el-table-column>
			<el-table-column prop="title" label="标签标题"></el-table-column>
			<el-table-column prop="url" label="跳转地址"></el-table-column>
			<el-table-column prop="target" label="跳转方式"></el-table-column>
			<el-table-column label="排序数字">
				<template slot-scope="scope">
					<!-- scope.row是每一行的数据 -->
					<el-tag type="success">{{ scope.row.slide_order }}</el-tag>
				</template>
			</el-table-column>
			<el-table-column label="状态">
				<template slot-scope="scope">
					<el-tag v-if="scope.row.usable === 1" type="success">启用</el-tag>
					<el-tag v-if="scope.row.usable === -1" type="danger">禁用</el-tag>
				</template>
			</el-table-column>
			<el-table-column label="添加时间">
				<template slot-scope="scope">
					<span>{{ scope.row.create_time }}</span>
				</template>
			</el-table-column>
			<el-table-column label="编辑时间">
				<template slot-scope="scope">
					<span>{{ scope.row.update_time }}</span>
				</template>
			</el-table-column>
			<el-table-column label="操作" width="300">
				<!-- 复杂结构的固定写法：slot-scope="scope" -->
				<template slot-scope="scope">
					<el-button v-permission="'promotion:slide:edit'" type="primary" plain icon="el-icon-edit"
						@click="openEditDialog(scope.row)">编辑
					</el-button>
					<el-button v-permission="'promotion:slide:switch'" type="info"
						@click="handleBanned(scope.row.slide_id, scope.$index)" v-if="scope.row.usable === 1" plain
						icon="el-icon-switch-button">禁用</el-button>
					<el-button v-permission="'promotion:slide:switch'" type="success"
						@click="handleCancel(scope.row.slide_id, scope.$index)" v-if="scope.row.usable === -1" plain
						icon="el-icon-switch-button">启用</el-button>
					<el-button v-permission="'promotion:slide:remove'" type="danger" plain icon="el-icon-delete"
						@click="handleRemove(scope.row.slide_id, scope.$index)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!-- 添加轮播 -->
		<el-dialog title="添加轮播图" :visible.sync="insert_dialog_visible" @close="handleCloseDialog('insert_form')">
			<el-form :model="insert_form" :rules="rules" ref="insert_form" label-width="100px">
				<el-form-item label="轮播图片" prop="picture">
					<UploadPhoto v-model="insert_form.picture"></UploadPhoto>
				</el-form-item>
				<el-form-item label="标题文字" prop="title">
					<el-input v-model="insert_form.title" placeholder="文字将作为标题,显示在图片上"></el-input>
				</el-form-item>
				<el-form-item label="链接地址:" prop="url">
					<el-input type="text" v-model="insert_form.url" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="跳转方式" prop="target ">
					<el-radio-group v-model="insert_form.target">
						<el-radio label="_blank">新窗口跳转</el-radio>
						<el-radio label="_self">本窗口跳转</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="显示排序" prop="slide_order">
					<el-input type="text" v-model="insert_form.slide_order" placeholder="请输入数字,数字越小,排序越靠前"></el-input>
				</el-form-item>
				<el-form-item class="bottom">
					<el-button type="primary" @click="insert_dialog_visible = false">取消</el-button>
					<el-button type="primary" @click="handleInsert">添加</el-button>
				</el-form-item>
			</el-form>
		</el-dialog>

		<!-- 编辑轮播图 -->
		<el-dialog title="添加轮播图" :visible.sync="edit_dialog_visible" @close="handleCloseDialog('edit_form')">
			<el-form :model="edit_form" :rules="rules" ref="edit_form" label-width="100px">
				<el-form-item label="轮播图片" prop="picture">
					<UploadPhoto v-model="edit_form.picture"></UploadPhoto>
				</el-form-item>
				<el-form-item label="标题文字" prop="title">
					<el-input v-model="edit_form.title" placeholder="文字将作为标题,显示在图片上"></el-input>
				</el-form-item>
				<el-form-item label="链接地址:" prop="url">
					<el-input type="text" v-model="edit_form.url" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="跳转方式" prop="target ">
					<el-radio-group v-model="edit_form.target">
						<el-radio label="_blank">新窗口跳转</el-radio>
						<el-radio label="_self">本窗口跳转</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="显示排序" prop="slide_order">
					<el-input type="text" v-model="edit_form.slide_order" placeholder="请输入数字,数字越小,排序越靠前"></el-input>
				</el-form-item>
				<el-form-item class="bottom">
					<el-button type="primary" @click="edit_dialog_visible = false">取消</el-button>
					<el-button type="primary" @click="handleEdit">保存</el-button>
				</el-form-item>
			</el-form>
		</el-dialog>
	</el-card>
</template>

<script>
import { Slide } from '@/api';
import UploadPhoto from '@/components/UploadPhoto.vue';
export default {
	name: 'List',
	components: { UploadPhoto },
	data() {
		return {
			tableData: [],
			insert_dialog_visible: false,
			edit_dialog_visible: false,
			headers: { Authorization: `Bearer ${sessionStorage.access_token}` },
			insert_form: {
				title: '',
				url: 'http://',
				target: '_blank',
				usable: 1,
				create_time: new Date().toLocaleString(),
				update_time: new Date().toLocaleString(),
				slide_order: '',
			},
			edit_form: {},
			rules: {
				picture: [{ required: true, message: "请上传一张轮播图！", trigger: 'blur' }],
				url: [
					{ required: true, message: "请填写网站地址！", trigger: 'blur' },
					{
						pattern: /^(http:\/\/|https:\/\/)?(www\.)?[a-z0-9]+\.[a-z]{2,}(\.[a-z]{2,})?$/i,
						message: '请填写合规的网址！',
						trigger: 'blur'
					}
				],
				target: [{ required: true, message: "请选择跳转方式！", trigger: 'blur' },],
				slide_order: [{ required: true, message: "请填写排序数字！", trigger: 'blur' },],
			},
			// 缓存当前操作的row--指针地址
			current_slide: '',
		}
	},
	// 在created或mounted发送ajax请求(通过调用函数)
	created() {
		document.title = "轮播图列表页";
		this.loadList();
	},
	methods: {
		// 一般将发送AJAX写到methods中
		// 加载列表
		async loadList() {
			let { status, msg, data } = await Slide.list({ pagesize: 20, pageindex: 1 });
			if (status) {
				this.tableData = data;
			} else {
				this.$message.error(msg);
			}
		},

		// 打开编辑弹窗
		openEditDialog(slide) {
			// 缓存当前操作的slide，为了后续的操作DOM，存的是指针地址
			this.current_slide = slide;
			// 还原表单数据，浅拷贝一个，让点击保存后才能生效(双向数据绑定在修改的同时内容跟着变，不符合实际需求)
			this.edit_form = { ...slide };
			// 打开弹窗
			this.edit_dialog_visible = true;
		},
		// 关闭弹窗，清除表单验证状态
		handleCloseDialog(formName) {
			// formName是变量，不能使用 ref.formName
			this.$refs[formName].resetFields();
		},
		// 添加轮播
		handleInsert() {
			this.$refs.insert_form.validate(async (valid) => {
				if (valid) {
					// 后台返回的data数据包含id，由后台返回
					let { status, msg, data } = await Slide.add({ ...this.insert_form });
					if (status) {
						// 操作 DOM -- 拷贝(单层对象-浅拷贝；多层对象-深拷贝)
						this.tableData.push({ ...this.insert_form, ...data });
						this.tableData.sort(function (slideA, slideB) {
							return slideA.slide_order - slideB.slide_order;
						});
						// 关闭弹窗
						this.insert_dialog_visible = false;
						// 添加成功信息提示
						this.$message.success(msg);
					} else {
						// 添加失败信息提示
						this.$message.error(msg);
					}
				}
			});
		},
		async handleEdit() {
			try {
				let valid = await this.$refs.edit_form.validate();
				if (valid) {
					// 发送AJAX
					let { status, msg } = await Slide.edit({ ...this.edit_form });
					if (status) {
						// 方法2
						Object.assign(this.current_slide, this.edit_form);
						this.tableData.sort(function (slideA, slideB) {
							return slideA.slide_order - slideB.slide_order;
						});
						// 关闭弹窗
						this.edit_dialog_visible = false;
						// 添加成功信息提示
						this.$message.success(msg);
					} else {
						// 添加失败信息提示
						this.$message.error(msg);
					}
				}
			} catch (error) {
				console.log(error);
			}
		},
		// 禁用
		handleBanned(slide_id, index) {
			this.$confirm('该操作将禁用该用户, 是否继续?', '提示', { type: 'warning' })
				.then(async () => {
					let { status, msg } = await Slide.usable({ slide_id, usable: -1 });
					if (status) {
						// 操作DOM
						this.tableData[index].usable = -1;
						// 信息提示
						this.$message.success(msg);
					} else {
						this.$message.error(msg);
					}
				}).catch(() => {
					this.$message.info("已取消该操作!");
				});
		},
		// 启用
		handleCancel(slide_id, index) {
			this.$confirm('该操作将启用该用户, 是否继续?', '提示', { type: 'warning' })
				.then(async () => {
					let { status, msg } = await Slide.usable({ slide_id, usable: 1 });
					if (status) {
						// 操作DOM
						this.tableData[index].usable = 1;
						// 信息提示
						this.$message.success(msg);
					} else {
						this.$message.error(msg);
					}
				}).catch(() => {
					this.$message.info("已取消该操作!");
				});
		},
		// 删除
		handleRemove(slide_id, index) {
			this.$confirm('此操作将永久删除该轮播图, 是否继续?', '警告', { type: 'warning' })
				.then(async () => {
					let { status, msg } = await Slide.remove({ slide_id });
					if (status) {
						// 操作 DOM
						this.tableData.splice(index, 1);
						// 信息提示
						this.$message.success(msg);
					} else {
						// 信息提示
						this.$message.error(msg);
					}
				}).catch(() => {
					this.$message.info('已取消删除！');
				});
		}
	},
}
</script>

<style>
.clearfix {
	display: flex;
	justify-content: space-between;
}

.avatar-uploader .el-upload {
	border: 1px dashed #d9d9d9;
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
}

.avatar-uploader .el-upload:hover {
	border-color: #409EFF;
}

.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	line-height: 178px;
	text-align: center;
}

.avatar {
	width: 178px;
	height: 178px;
	display: block;
}

.bottom {
	display: flex;
	justify-content: flex-end;
}
</style>
